import { createStore } from "vuex";
import axios from "axios";
import { reject } from "lodash";
// 创建一个新的 store 实例
const store = createStore({
  state() {
    return {
      counter: 100,
      name: "why",
      age: 18,
      books: [
        { name: "深入VueJs", price: 200, count: 3 },
        { name: "深入Javascript", price: 300, count: 4 },
        { name: "深入React", price: 400, count: 5 },
        { name: "深入Node", price: 500, count: 6 },
      ],
      discount: 0.6,
      banners:[]
    };
  },
  mutations: {
    increment(state) {
      state.counter++;
    },
    increment_n(state,payload) {
      state.counter+= payload;
    },
    decrement(state) {
      state.counter--;
    },
    decrement_n(state,payload) {
      state.counter-= payload;
    },
    addBannerData(state,payload){
      state.banners = payload
    }
  },
  getters: {
    totalPrice(state,getters) {
      let totalPrice = 0;
      state.books.map((item) => {
        totalPrice += item.price * item.count;
        return item;
      });
      return totalPrice * getters.currentDiscount;
    },
    currentDiscount(state) {
      return state.discount * 0.9;
    },
    totalPriceGreaterN(state, getters) {
      return (n) => {
        let totalPrice = 0;
        state.books.map((item) => {
          if (item.count > n) {
            totalPrice += item.price * item.count;
          }
          return item;
        });
        return totalPrice * getters.currentDiscount;
      };
    },
    nameInfo(state){
      return state.name
    },
    ageInfo(state){
      return state.age
    }
  },
  actions:{
    // 1.参数问题和进行异步操作
    incrementAction(context,payload){
      setTimeout(()=>{
        context.commit('increment')
      },1000)
    },
    decrementAction(context){
      context.commit('decrement')
    },
    // 2.可以接受promise对象和进行异步操作
     getHomeMultidata(context,payload){
      return new Promise(async(resolve,reject)=>{
        try {
          const res = await axios.get('http://123.207.32.32:8000/home/multidata')
          context.commit('addBannerData',res.data.data.banner.list);
          resolve('获取数据成功~');
        } catch (err) {
          reject(err)
        }
      })
      // return new Promise((resolve,reject)=>{
      //   axios.get('http://123.207.32.32:8000/home/multidate').then(res =>{
      //     context.commit('addBannerData',res.data.data.banner.list)
      //     resolve('拿到数据~')
      //   }).catch(err=>{
      //     reject(err)
      //   })
      // })
    },
  }
});

export default store;
